package com.ktjy.sample.aop;

import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect // 声明这是一个切面
@Component //结合扫描包 产生bean对象注入到Ioc容器中
public class TransactionAspect {
    private static final Logger logger= LoggerFactory.getLogger(TransactionAspect.class);
    @Pointcut("execution(* com.ktjy.sample.service.*.*(..))")
    public void pt(){}

    @Before(value = "pt()") //声明这是一个切点
    public void before(){
        logger.info("[TransactionAspect前置增强]模拟打开数据库连接并开启事物...");
        logger.info("SqlSession sqlSession=MyBatisUtil.createSqlSession(false);\n");
    }
    @AfterReturning(value = "pt())",returning = "result")
    public void afterReturning(Object result){
        logger.info("[TransactionAspect后置增强]模拟正常完成业务提交事物...");
        logger.info("sqlSession.commit();");
    }
    @AfterThrowing(value = "pt())",throwing = "e")
    public void afterThrowing(Throwable e){
        logger.info("[TransactionAspect异常抛出增强]模拟业务异常回滚事物,异常详细为:"+e.getMessage());
        logger.info("sqlSession.rollback();");
    }
    @After(value = "pt())")
    public void after(){
        logger.info("[TransactionAspect最终增强]模拟关闭数据库连接...");
        logger.info("MyBatisUtil.closeSqlSession(sqlSession);");
    }
}
